/**
* This class implements SPA Utility functions
*
* A web service will delete SPA records if the records
* are untouched (i.e. not submitted after 80 hours of created date)
* 
* This deleteSPA webservice can be triggered through Apex Scheduler
* or @FUTURE annotation on update trigger for SPA object
*
* Author - Sayeed Faruqi
* Company - Cognizant Technology Solutions
* Client - Linksys (Cisco)
* Last Mofified BY - Manu Dhingra
* Last Update - March, 2010
**/ 

global class SPAUtilProcess {
   
    //The following webservice will delete inactive SPA records
    webservice static void deleteSPA()  {
        // Set a time marker to delete records older than 80 hours = 3.33 days
        datetime dt = system.now() - 0.1;
        System.debug ('The time for deletion marker is: ' + dt);
        
        SPA__c[]  sp =  [SELECT Id, SPAId__c, createddate, ownerid, owner.email, owner.FirstName, owner.id FROM SPA__c 
                            WHERE (status__c ='Incomplete' AND createddate < :dt)
                            OR
                            (status__c ='Recalled' AND lastmodifieddate < :dt)];
        //The following loop will send the deletion emails to SPA owner
        for (SPA__c s:sp) {
            string toAddress = [select email, id from user where id = :s.ownerId].email;
            system.debug('Email address of the SPA owner is: '+ toAddress);
            messaging.singleEmailMessage mail = new messaging.singleEmailMessage();
            mail.setToAddresses(new String[] {s.owner.Email});
            mail.setTargetObjectId(s.owner.id);
            //mail.settemplateId('00XQ0000000LzkG');
            mail.setSubject('SPA '+ s.SPAId__c + ' deleted');
            mail.setReplyTo ('SPASupport@cisco.com');
            mail.setHtmlBody('<p>' +s.owner.firstname+',</p>'+
                    '<p> On ' + s.createdDate + ' you created SPA# '+s.SPAId__c+
                    ' but did not create discount items for this SPA or neglected to submit it for approval. Due to the amount of time this SPA has remained incomplete in the system ( >80 hours),it has been deleted.</p>');
            
            mail.setSaveAsActivity(false);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
        //Finally delete the inactive SPA records
        delete sp;
    }
    
    // The following webservice will update the util flag for SPA records
    // this update will force workflow rule to be reevaluated
    // and will remove email alerts from the timebased actions queue
    // this is required because SFDC doesn't trigger a workflow if the field is
    // updated through field update feature of an approval flow
    
    public static void CheckSPAUtilFlag()  {
        SPA__c[]  sp1 =  [SELECT Id, SPAid__c, utilflag__c ,status__c
                        FROM SPA__c 
                        WHERE (status__c ='Submitted'
                        AND utilflag__c = FALSE)
                        OR status__c ='Recalled' OR ((status__c = 'Approved') AND utilflag__c = TRUE)];
        // let's check the flag
        for (SPA__c s : sp1) {
            if (s.status__c == 'Submitted' )
            	s.utilflag__c = TRUE;
            else
            	s.utilflag__c = FALSE;
            system.debug ('Util flags are checjed for SPA Id: ' + s.SPAid__c);
        }
        update sp1;
    }

    //test method
    @isTest
    static void testSPA(){
            SPAUtilProcess.deleteSPA();
            
            SPAUtilProcess.CheckSPAUtilFlag();
    }
}